package br.com.site.fiolaser.util;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.swing.text.MaskFormatter;

public class CNPJConverter implements Converter{

	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) throws ConverterException {
		   
		System.out.println("getAsObject="+arg2);
		
		if( arg2 != null ){
		
			String var = arg2.replaceAll("/", "");
			
			var = var.replaceAll("-", "");
			
			var = var.replaceAll("\\.", "");
			
			if( var != null && !var.equals("") ){
				
				return new Long( var );
				
			}else{
				
				return null;
				
			}
			
		}else{
			
			return null;
			
		}
		
	}
	
	public String preencheCnpjComZero(String cnpj){
		if (cnpj.length() <14){
			return String.format("%014d", Long.valueOf(cnpj));
		}
		return cnpj;
	}

	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) throws ConverterException {
				
		if( arg2 != null){
			
			arg2 = preencheCnpjComZero(arg2.toString());
				
				   try{   
						  
			           MaskFormatter mf = new javax.swing.text.MaskFormatter("##.###.###/####-##");   
			  
			           mf.setValueContainsLiteralCharacters(false);
			           
			           if(arg2 != null && !arg2.equals("")){
			   	    		
			        	   return mf.valueToString(arg2);
			        	   
			           }else{
			        	   
			        	   return null;
			        	   
			           }
			  
			        }catch (Exception e){
			        	
			        	System.out.println("----------------------------------------------------");
			        	
			        	System.out.println(e.getMessage());
			        	
			        	System.out.println("-----------------------------------------------------");
			    
			        	return null;
			        	
			        }
	        
			}else{
				
				return null;
				
			}
		
	}
	
}